package com.wei.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wei.entity.Banner;
import com.wei.service.BannerService;
import com.wei.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author wjx
 * @ClassName BannerController
 * @description: TODO
 * @date 2022-12-02 12:50
 * @version: 1.0
 */
@RestController
@RequestMapping("/eduban/banner")
public class BannerController {
    @Autowired
    private BannerService bannerService;

    //TODO 可以在后台做一个banner管理 CRUD

    @GetMapping("/getBanner")
    @Cacheable(value = "banner", key = "'indexBanner'")
    public R getBanner() {
        //根据时间降序排列，获取前4条数据做返回
        LambdaQueryWrapper<Banner> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Banner::getGmtCreate).last("limit 4");

        List<Banner> bannerList = bannerService.list(queryWrapper);

        return R.ok().data("bannerList", bannerList);
    }

    /**
     * 获取banner
     *
     * @return
     */
    @GetMapping("/getBanner/{page}/{limit}")
    public R getBanner(@PathVariable long page, @PathVariable long limit) {
        Page<Banner> page1 = new Page<>(page, limit);
        bannerService.page(page1);
        return R.ok().data("bannerList", page1.getRecords()).data("total", page1.getTotal());
    }

    @PostMapping("addBanner")
    public R addBanner(@RequestBody Banner banner) {
        bannerService.save(banner);
        return R.ok();
    }

    @PutMapping("update")
    public R updateBanner(@RequestBody Banner banner) {
        bannerService.updateById(banner);
        return R.ok();
    }

    @DeleteMapping("remove/{id}")
    public R deleteBanner(@PathVariable String id) {
        bannerService.removeById(id);
        return R.ok();
    }
}
